<script setup lang="ts">
import {
  delRoleUserAPI,
  getRoleDetailAPI,
  getRoleListAPI,
  getRoleUserAPI,
  getTreeListAPI,
} from "@/apis/system";
import type { Role, RoleData, RoleUser } from "@/types/system";
import { onMounted, ref } from "vue";
import user from "@/assets/user.svg";
import activeUser from "@/assets/user-active.svg";
import { ElMessage, type ElTree } from "element-plus";
import router from "@/router";

const roleList = ref<Role[]>([]);
const getRoleList = async () => {
  const res = await getRoleListAPI();
  roleList.value = res.data;
  // 第一次获取
  getRoleUserList(roleList.value[activeIndex.value].roleId!);
};
onMounted(async () => {
  await getRoleList();
  await getTreeList();
  // 默认选中第一个角色
  getRoleDetail(roleList.value[0].roleId + "");
});

// 2. 点击激活交互
const activeIndex = ref(0);
const changeRole = (idx: number) => {
  activeIndex.value = idx;
  // 2.1 获取激活的角色的角色ID
  const roleId = roleList.value[idx].roleId;
  getRoleDetail(roleId + "");
  getRoleUserList(roleId!);
};
// 获取当前角色权限点
const rolePerms = ref<number[]>([]);
// 6. 高亮tree节点
const treeRef = ref<InstanceType<typeof ElTree>[]>();
// 5. 根据角色id获取角色详情(权限点和角色信息)
const getRoleDetail = async (roleId: string) => {
  const res = await getRoleDetailAPI(roleId);
  console.log(res);
  // 5.1 遍历
  console.log(treeRef.value, res);
  treeRef.value?.forEach((tree, index) => {
    // @ts-expect-error
    tree.setCheckedKeys(res.data.perms[index]);
  });
  rolePerms.value = res.data.perms;
};

// 3. 获取权限列表
const treeList = ref<RoleData[]>([]);
const getTreeList = async () => {
  const res = await getTreeListAPI();
  treeList.value = res.data;
  // 禁用
  // 目标：treeList里面的每一项以及嵌套的子项都添加一个disabled = true
  addDisabled(treeList.value);
};

// 4. 递归处理函数
const addDisabled = (treeList: RoleData[]) => {
  treeList.forEach((item) => {
    item.disabled = true;
    // 递归处理
    if (item.children) {
      addDisabled(item.children);
    }
  });
};

// 7. tab切换
const activeName = ref("tree");

// 8. 获取当前角色下的所有成员
const roleUserList = ref<RoleUser[]>([]);
// 封装获取当前角色下的成员的方法
const getRoleUserList = async (roleId: number) => {
  const res = await getRoleUserAPI(roleId);
  roleUserList.value = res.data.rows;
};

// 9. 触发编辑和删除
const handleCommand = (command: string, roleId: number) => {
  if (command === "del") {
    delRole(roleId);
  }
  if (command === "edit") {
    router.push(`/roleAdd?roleId=${roleId}`);
  }
};
const delRole = async (roleId: number) => {
  await delRoleUserAPI(roleId);
  ElMessage({
    type: "success",
    message: "删除角色成功",
  });
  activeIndex.value = 0;
  await getRoleList();
  getRoleDetail(roleList.value[0].roleId + "");
};
</script>

<template>
  <div class="role-container">
    <div class="left-wrapper">
      <div
        class="role-item"
        :class="{ active: activeIndex === index }"
        v-for="(item, index) in roleList"
        :key="item.roleId"
        @click="changeRole(index)">
        <el-tooltip effect="dark" :content="item.remark" placement="top">
          <div class="role-info">
            <img
              :src="activeIndex === index ? activeUser : user"
              class="icon" />
            {{ item.roleName }}
          </div>
        </el-tooltip>
        <div class="more">
          <el-dropdown @command="handleCommand($event, item.roleId!)">
            <img src="@/assets/more.svg" class="icon" />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit">编辑角色</el-dropdown-item>
                <el-dropdown-item command="del">删除角色</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <el-button class="addBtn" size="small" @click="$router.push('/roleAdd')"
        >添加角色</el-button
      >
    </div>
    <div class="right-wrapper">
      <!-- 功能权限、成员列表 -->
      <el-tabs type="border-card" v-model="activeName">
        <el-tab-pane label="功能权限">
          <div class="tree-wrapper">
            <div v-for="item in treeList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>
              <el-tree
                ref="treeRef"
                :data="item.children"
                node-key="id"
                :props="{ label: 'title' }"
                show-checkbox
                check-strictly
                :default-expand-all="true" />
            </div>
          </div>
        </el-tab-pane>
        <!-- <el-tab-pane :label="`成员列表(${roleUserList.length})`" name="member"
          >成员管理</el-tab-pane
        > -->
        <el-tab-pane :label="`成员列表(${roleUserList.length})`" name="member">
          <div class="user-wrapper">
            <el-table :data="roleUserList">
              <el-table-column type="index" width="250" label="序号" />
              <el-table-column prop="name" label="员工姓名" />
              <el-table-column prop="userName" label="登录账号" />
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped lang="scss">
.role-container {
  display: flex;
  font-size: 14px;
  background-color: #fff;

  .left-wrapper {
    width: 200px;
    border-right: 1px solid #e4e7ec;
    padding: 4px;
    text-align: center;

    .role-item {
      position: relative;
      height: 56px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      cursor: pointer;

      &.active {
        background: #edf5ff;
        color: #4770ff;
      }
    }

    .role-info {
      display: flex;
      align-items: center;

      .icon {
        margin-right: 10px;
        width: 20px;
      }
    }

    .more {
      display: flex;
      align-items: center;
      .icon {
        width: 15px;
      }
    }

    .addBtn {
      width: 100%;
      margin-top: 20px;
    }
  }

  .right-wrapper {
    flex: 1;

    .tree-wrapper {
      display: flex;
      justify-content: space-between;

      .tree-item {
        flex: 1;
        border-right: 1px solid #e4e7ec;
        padding: 0px 4px;
        text-align: center;

        .tree-title {
          background: #f5f7fa;
          text-align: center;
          padding: 10px 0;
          margin-bottom: 12px;
        }
      }
    }

    ::v-deep .el-tabs__nav-wrap {
      padding-left: 20px;
    }

    .user-wrapper {
      padding: 20px;
    }
  }
}
</style>
